package com.xt.base.wireless.server.socket;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

/**
 *  <br>
 * <br>
 * 
 * <p>
 * <a href="ConnectionPool.java.html"><i>查看源文件</i></a>
 * </p>
 * 
 * @author 杨洪波
 * @create-date:2010-9-25
 */
public class SocketConnectionPool extends Thread{
	Logger log = Logger.getLogger(getClass());
	private static List<SocketServerThread> serverThreadLt = new ArrayList<SocketServerThread>();
	
    private long maxIdleTime=15*60*1000;			//<!-- 最大空闲时间(秒) -->
    private long idleConnectionTestPeriod=10*1000;//<!-- 坏死(空闲)连接回收线程间隔时间 -->
    
    /** 连接池为移动服务提供的监听端口*/
    private int port=13826;
    
    /**
     * 提供给Spring使用，把移动连接池集成到Spring中。
     */
    public SocketConnectionPool(){}

    /**
     * 当用户需要自己new一个移动连接池时，使用此方法。
     * @param file 连接池的配置文件。
     */
	public SocketConnectionPool(File file){
		
		if(!file.exists()){//文件不存在时，使用默认值
			log.warn("MConnectionPoolConfig.xml文件在classpath下不存在！已启用默认配置！");
			return ;
		}
		
		SAXReader reader = new SAXReader();
		try {
			Document doc = reader.read(file);
			Element root = doc.getRootElement();
			String maxIdleTimeStr  = root.element("maxIdleTime").getTextTrim();
			String idleConnectionTestPeriodStr  = 
				root.element("idleConnectionTestPeriod").getTextTrim();
			if(StringUtils.isNotEmpty(maxIdleTimeStr)){
				maxIdleTime = Long.valueOf(maxIdleTimeStr);
			}
			if(StringUtils.isNotEmpty(maxIdleTimeStr)){
				idleConnectionTestPeriod = Long.valueOf(idleConnectionTestPeriodStr);
			}
		}catch (DocumentException e) {
			log.error("在无线服务器端构造连接池时出错",e);
		}
	}
    
	public void add(SocketServerThread st){
		serverThreadLt.add(st);
	}
	
	public void run() {
		try {
			while (true) {
				for (SocketServerThread st : serverThreadLt) {
					if (st.isBaded() || st.isIdleClosed(maxIdleTime)) {
						serverThreadLt.remove(st);
						st.close();
					}
				}
				sleep(idleConnectionTestPeriod);
			}
		} catch (InterruptedException e) {
			throw new RuntimeException("挂起扫描连接池抛出异常", e);
		}
	}

	public long getMaxIdleTime() {
		return maxIdleTime;
	}

	public void setMaxIdleTime(long maxIdleTime) {
		this.maxIdleTime = maxIdleTime;
	}

	public long getIdleConnectionTestPeriod() {
		return idleConnectionTestPeriod;
	}

	public void setIdleConnectionTestPeriod(long idleConnectionTestPeriod) {
		this.idleConnectionTestPeriod = idleConnectionTestPeriod;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}
	
}
